var express = require('express');
var router = express.Router();
const sequelize = require('../db/connection.js');
const { QueryTypes } = require('sequelize');
const { Choose, Question } = require('../entity/question.js');
const { Result } = require('../entity/result.js');


/* GET users listing. */
router.get('/all',async function(req, res, next) {
  let questionResult = await getQuestion();  
  //先将结果映射成Question列表
  let choList = questionResult.map((value,index,array) =>{
    let ques = new Question(value.cho_id,value.content,value.type)
    return ques
  })
  
  //获取全部的选项源
  let answResult = await getAllAnswers();
  //开始为每个题目装配选项
  for(let i = 0;i < choList.length;i++){
      let count = 0;
      for(let j = 0;j < answResult.length;j++){
          let answTemp = answResult[j]
          if(choList[i].id === answTemp.cho_id){
            let newChoose = new Choose(answTemp.sel_id,answTemp.s_content,answTemp.ack)
            choList[i].selectList.push(newChoose)
            count++
          }
          if(count >= 4){
            break
          }
      }
  }
  let result = new Result(200,'成功',choList);
  res.send(JSON.stringify(result));
});

router.get('/single',async function(req, res,next ) {
    
})

 //先从t_cho表中获取固定数量的选择题 从中应该可以获取题目的id信息
async function getQuestion(page=1,num=10,type=-1){
  let sql = 
      `select cho_id,content,type
       from t_cho
       where 1 = 1
       `
  if(type !== -1){
    
    if(type === 0){//判断题
      sql = sql.concat(`
         and type = 0 
        `)
    }else if(type === 1){//选择题
      sql = sql.concat(`
         and type = 1        
        `)
    }else if(type === 2){//
      sql = sql.concat(`
        and type = 2        
       `)  
    }
  }
  sql = sql.concat(`
    limit ${num * (page - 1)},${num}
    `)
  
  let result = await sequelize.query(
      sql,
      {
      type:QueryTypes.SELECT
      })
    return result;
}
//(有没有一种可能，没有必要使用临时表，干脆把连接的数据先全部丢到内存中)
//根据选择题id左连接对应的选项
async function getAllAnswers(){
    let result = await sequelize.query(
      `select cs.*,ts.s_content
       from t_cho_sel cs
       left join t_sel ts
      on cs.sel_id = ts.sel_id`,
      {
        type:QueryTypes.SELECT
      }
    );
    return result;
}



module.exports = router;
